package com.cookie.controller;

import com.cookie.api.exception.JsonResponseException;
import com.cookie.api.model.PO.Result;
import com.cookie.api.model.PO.User;
import com.cookie.api.model.VO.UserVO;
import lombok.Data;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author DELL
 */
@Controller
@RequestMapping("")
@ApiIgnore
public class AuthController {
    protected HttpServletRequest request;
    protected HttpServletResponse response;

    @PostMapping(value = "/login", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Result<String> login(@RequestBody LoginParam param) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(param.getName(), param.getPassword());
        try {
            subject.login(token);
        } catch (Exception e) {
            throw new JsonResponseException(e.getMessage());
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(subject.getPrincipal(), userVO);
        request.getSession().setAttribute("user", userVO);
        return new Result<>("200", "user.login.success", "dashboard");
    }

    @GetMapping(value = "/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/";
    }


    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
    }

    @Data
    private static class LoginParam {
        private String name;
        private String password;
    }

}
